package com.ltwc.lttv.tools

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build

class PackageUtil(private val context: Context) {

    // 获取已安装应用的 PackageInfo 列表
    fun getInstalledPackages(): List<PackageInfo> {
        val packageManager = context.packageManager
        return packageManager.getInstalledPackages(PackageManager.GET_META_DATA)
    }

    // 根据包名获取 PackageInfo
    fun getPackageInfo(packageName: String): PackageInfo? {
        val packageManager = context.packageManager
        val flag = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            PackageManager.GET_SIGNATURES
        } else {
            PackageManager.GET_SIGNING_CERTIFICATES
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
            return try {
                packageManager.getPackageInfo(packageName, flag)
            } catch (e: PackageManager.NameNotFoundException) {
                null;
            }

        } else {
            return try {
                packageManager.getPackageInfo(
                    packageName,
                    PackageManager.PackageInfoFlags.of(PackageManager.GET_SIGNING_CERTIFICATES.toLong()))
            } catch (e: PackageManager.NameNotFoundException) {
                null;
            }
        }
    }

    // 根据包名判断应用是否已安装
    fun isPackageInstalled(packageName: String): Boolean {
        return getPackageInfo(packageName) != null
    }
}